<template>
  <section>
    <el-dialog
      title="设置角色"
      :visible.sync="visible"
      :value="value" 
      width="600px"
    >
      <!--<el-form
        ref="roleForm">
        <el-form-item 
          label="所属应用" 
          :label-width="labelWidth" 
          prop="appId">
          <el-select
            v-model="powerInfo.appId" 
            @change="loadRoleInfo"
            placeholder="请选择应用">
            <el-option
              v-for="(item,index) in applications"
              :key="index"
              :label="item.code +' - ' +item.description"
              :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>-->
      <el-transfer
        v-model="powerInfo.selectedIds"
        :data="roles"
        :titles="['待选角色','已选角色']"
        filterable
        filter-placeholder="请输入角色名称"
        :props="{
          key: 'id',
          label: 'description'
        }"
      />
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="small"
          @click="cancle"
        >取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="submit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<style>
</style>
<script>
export default {
  name: "UserRole",
  data() {
    return {
      visible: false,
      labelWidth: "",
      // applications: [],
      roles: [],
      powerInfo: {
        selectedIds: [],
        id: 0
        // appId: null
      }
    };
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler: function(val) {
        this.visible = val.show && val.type === "role";
        this.labelWidth = val.formLabelWidth || "120px";
        this.powerInfo.id = val.id;
        // this.applications = val.applications;
        if (val.id) {
          this.loadRoleInfo();
        }
      }
    },
    visible(val) {
      if (!val) this.$emit("on-show-change", this.$data);
    }
  },
  methods: {
    loadRoleInfo() {
      this.$api.user.getUserRoles(
        this.powerInfo.id,
        // this.powerInfo.appId,
        result => {
          this.roles = result.infos;
          this.powerInfo.selectedIds = result.infos
            .filter(item => item.selected)
            .map(item => item.id);
        }
      );
    },

    cancle() {
      this.visible = false;
      this.powerInfo = {
        selectedIds: [],
        id: 0
      };
    },
    submit() {
      this.$api.user.grantRole(this.powerInfo, () => {
        this.$message({
          type: "success",
          message: "授权成功",
          onClose: this.cancle
        });
      });
    }
  },
  props: {
    value: {
      type: Object,
      default: function() {
        return {
          show: false,
          formLabelWidth: "120px",
          id: 0
          // applications: []
        };
      }
    }
  }
};
</script>
